package ge.telasi.tasks.controller;

import ge.telasi.tasks.model.Task;
import ge.telasi.tasks.model.User;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 * @author dimitri
 */
public class AnalyzeController {

    public List getTasksCompletedReport(EntityManager em, User me, Calendar c1, Calendar c2) {
        List list = new ArrayList();
        List<User> users = new UserController().getAllActiveUsers(em, null);

        for (User user : users) {
            Map row = new HashMap();
            row.put("id", user.getId());
            row.put("username", user.getUsername());
            row.put("fullname", user.getFullName());
            int open = 0;
            int complete = 0;
            int closed = 0;
            int all = 0;

            Query q = em.createNativeQuery("SELECT t.task_status as task_status, count(*) as task_count "
                + " FROM tasks t INNER JOIN task_receivers r ON t.id = r.task_id "
                + " WHERE r.user_id = ? AND t.owner_id = ? AND t.created BETWEEN ? AND ? "
                + " GROUP BY t.task_status ")
                .setParameter(1, user.getId())
                .setParameter(2, me.getId())
                .setParameter(3, c1)
                .setParameter(4, c2)
                ;

            List results = q.getResultList();
            for (Object res : results) {
                Vector resArray = (Vector) res;
                int status = ((BigDecimal) resArray.get(0)).intValue();
                int count = ((BigDecimal) resArray.get(1)).intValue();
                all += count;
                if (status == Task.STATUS_DRAFT || status == Task.STATUS_OPEN || status == Task.STATUS_PAUSED) {
                    open += count;
                } else if (status == Task.STATUS_COMPLETE_OK || status == Task.STATUS_COMPLETE_CANCEL) {
                    complete += count;
                } else if (status == Task.STATUS_CLOSED_OK || status == Task.STATUS_CLOSED_CANCEL) {
                    closed += count;
                }
            }

            row.put("open", open);
            row.put("complete", complete);
            row.put("closed", closed);
            row.put("all", all);
            list.add(row);
        }

        return list;
    }

}
